package com.lyf.language.practice.practice_6_21.io.network.tcpv1;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * @author LYF
 * @date 2022/6/22
 */
public class TcpSocketClient {

    /**
     * 客户端程序
     */
    public void client() throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("waiting connect server!");
        Socket socket = new Socket("127.0.0.1", 8888);
        System.out.println("connect successfully!");
        while (true) {
            // 给服务端发点东西
            System.out.print("enter:");
            //String s = scanner.next();
            String s = scanner.nextLine();
            if ("exit".equals(s)) {
                break;
            }
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write(s.getBytes(StandardCharsets.UTF_8));
            byte[] bytes = new byte[1024];

            // 读一下服务端发来的东西
            InputStream inputStream = socket.getInputStream();
            int read = inputStream.read(bytes);
            System.out.println("server:" + new String(bytes, 0, read, Charset.defaultCharset()));


        }
    }

    public static void main(String[] args) throws IOException {
        TcpSocketClient tcpSocketServer = new TcpSocketClient();
        tcpSocketServer.client();
    }
}
